// index.js
import { getBanners, getSongMenu } from "../../service/api_music"
import qureyRect from "../../utils/query-rect"
import { rankingStore, playerStore } from '../../store/index'

Page({
  data: {
    isPlaying:false,
    playAnimationState:'paused',
    swiperHeight: 0,
    banners: [],
    hotSongMenu: [],
    recommendMenu: [],
    recommendSongs: [],
    currentSong: {}
  },
  onLoad: function (options) {
    // playerStore.dispatch("playMusicWithSongIdAction",{id:2030160666})
    //获取页面数据
    this.getPageData()
    //发起共享数据的请求
    rankingStore.dispatch("getRankingData")
    //从store获取共享数据
    this.setupPlayStoreListener()

  },
  //网络请求
  getPageData() {
    getBanners().then(res => {
      // setData在设置data数据上，是同步的
      //通过最新的数据对wxml进行渲染，渲染的过程是异步的
      this.setData({ banners: res.data.banners })
    }),
      getSongMenu().then(res => {
        this.setData({ hotSongMenu: res.data.playlists })
      }),
      getSongMenu("华语").then(res => {
        this.setData({ recommendMenu: res.data.playlists })
      })
  },
  //图片加载完毕后事件
  swiperImageLoaded:function() {
    // 获取图片的高度（组件的高度）
    qureyRect(".banner-image").then(res => {
      if (res.length > 0) {
        this.setData({ swiperHeight: res[0].height })
      }
    })
  },
  handleSearchClick:function() {
    wx.navigateTo({
      url: '../detail-search/index',
    })
  },
  handleSongItemClick:function(event) {
    const index = event.currentTarget.dataset.index
    playerStore.setState("songPlayList", this.data.recommendSongs)
    playerStore.setState('songPlayListIndex', index)
  },
  handlePlayBtnClick:function(event){
    playerStore.dispatch('changeMusicPlayStatusAction',this.data.isPlaying)
    //阻止冒泡，小程序中没有这个方法，不可使用
    // event.stopPropagation()
  },
  handlePlayBarClick:function(){
    wx.navigateTo({
      url: '/pages/music-player/index',
    })
  },
  handleMoreClick: function () {
    this.navigateToMoreSongs('newRanking')
  },
  //从store获取共享数据
  setupPlayStoreListener: function () {
    // 排行榜监听
    rankingStore.onState("newRanking", (res) => {
      if (res.length === 0) return
      const recommendSongs = res.slice(0, 6)
      this.setData({ recommendSongs })
    })
    // 播放器监听
    playerStore.onStates(["currentSong","isPlaying"], ({ currentSong,isPlaying }) => {
      if (currentSong) {
        this.setData({ currentSong })
      }
      if (isPlaying!==undefined) {
        this.setData({
          isPlaying,
          playAnimationState:isPlaying?'runnning':'paused'
        })
      }
    })
  },

  navigateToMoreSongs: function (rankingName) {
    wx.navigateTo({
      url: `/pages/songs-more/index?rankingName=${rankingName}&type=rank`,
    })
  }
})
